import { defineStore } from "pinia";
import { useCargoStore } from "./cargo";
import { reactive } from "vue";
import { useMapStore } from "./map";
import { usePlayerStore } from "./player";
import { useTargetStore } from "./target";
import { GameData } from "../game/gameData";

interface Game {
    isGameCompleted:boolean
    level:number
}

export const useGameStore = defineStore('gameStore',() => {
    const game = reactive<Game>({
        isGameCompleted:false,
        level:1
    })

    let _gameData:GameData

    // 检测安置点
    function detectionGameCompleted() {
        const { cargos } = useCargoStore()
        game.isGameCompleted =  cargos.every((cargo) => cargo.onTarget)
    } 
    function setupGame(gameData:GameData) {
        _gameData = gameData
        setupLevel()
    }
    function toNextLevel() {
        game.level += 1
        game.isGameCompleted = false
        setupLevel()
    }

    function setupLevel() {
        const levelGameData = _gameData[game.level - 1]

        const { createCargo,addCargo,cleanAllCargos } = useCargoStore()
        const { addTarget,createTarget,cleanAllTargets } = useTargetStore()
        const { player } = usePlayerStore()
        const { setupMap } = useMapStore()
        
        player.x = levelGameData.player.x
        player.y = levelGameData.player.y
        
        setupMap(levelGameData.map)
        
        cleanAllCargos()
        levelGameData.cargos.forEach(cargo => {
            addCargo(createCargo({x:cargo.x,y:cargo.y}))
        })
        cleanAllTargets()
        levelGameData.targets.forEach(target => {
            addTarget(createTarget({x:target.x,y:target.y}))
        })
    }

    return {
        game,
        detectionGameCompleted,
        setupGame,
        toNextLevel
    }
})